package com.ruoyi.web.controller.common;

import com.ruoyi.db.domain.SseEvent;
import com.ruoyi.laiqianba.enums.SseEventType;
import com.ruoyi.laiqianba.manager.SseConnectionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/api/sse")
@Slf4j
public class SseController {
    
    @Autowired
    private SseConnectionManager sseConnectionManager;
    
    /**
     * 建立SSE连接
     */
    @GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter connect(HttpServletRequest request) {
        String clientId = generateClientId(request);
        log.info("SSE连接建立: clientId={}", clientId);

        SseEmitter emitter = sseConnectionManager.addConnection(clientId);

        // 发送连接成功事件
        SseEvent connectEvent = SseEvent.of(
            "CONNECT_SUCCESS",
            Map.of("clientId", clientId, "timestamp", new Date()),
            "SSE连接建立成功"
        );

        try {
            emitter.send(SseEmitter.event()
                    .id(connectEvent.getEventId())
                    .name(connectEvent.getEventType())
                    .data(connectEvent));
        } catch (Exception e) {
            log.error("发送连接成功事件失败", e);
        }

        return emitter;
    }
    
    /**
     * 关闭SSE连接
     */
    @PostMapping("/disconnect")
    public ResponseEntity<?> disconnect(HttpServletRequest request) {
        String clientId = generateClientId(request);
        sseConnectionManager.removeConnection(clientId);
        log.info("SSE连接关闭: clientId={}", clientId);
        return ResponseEntity.ok(Map.of("message", "连接已关闭"));
    }
    
    /**
     * 测试发送消息
     */
    @PostMapping("/test-send")
    public ResponseEntity<?> testSend(@RequestParam String message) {
        SseEvent event = SseEvent.of(
            SseEventType.SYSTEM_NOTIFICATION.getCode(),
            Map.of("testMessage", message),
            "测试消息: " + message
        );
        
        sseConnectionManager.broadcast(event);
        return ResponseEntity.ok(Map.of("message", "测试消息发送成功"));
    }
    
    /**
     * 生成客户端ID
     */
    private String generateClientId(HttpServletRequest request) {
        String sessionId = request.getSession().getId();
        String remoteAddr = request.getRemoteAddr();
        return DigestUtils.md5DigestAsHex((sessionId + remoteAddr).getBytes());
    }
}